package com.splashcard.net;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.splashcard.cardsFace.SplashCard;
import com.splashcard.usecase.TestCard;

public class SplashClient {
	private final static Logger logger = Logger.getLogger(SplashClient.class
			.getName());
	
	public interface ClientCallBack{
		public void OnCallBack(Object object);
	}

	public  Object send(String targetName, int port, Object object) {
		Socket socket = null;
		ObjectOutputStream os = null;
		ObjectInputStream is = null;

		try {
			socket = new Socket(targetName, port);
			os = new ObjectOutputStream(socket.getOutputStream());
			os.writeObject(object);
			os.flush();

			is = new ObjectInputStream(new BufferedInputStream(
					socket.getInputStream()));
			Object obj = is.readObject();
			return obj;
		} catch (IOException ex) {
			logger.log(Level.SEVERE, null, ex);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (Exception ex) {
			}
			try {
				os.close();
			} catch (Exception ex) {
			}
			try {
				socket.close();
			} catch (Exception ex) {
			}
		}
		return null;
	}
	
	public void send(final CardSet cardSet,final ClientCallBack clientCallBack) {
		new Thread(){
			public  void run() {
				Object object =  send(cardSet.getTargetName(), cardSet.getPort(), cardSet);
				if(clientCallBack!=null){
					clientCallBack.OnCallBack(object);
				}
			};
		}.start();
		
	}

	public static void main(String[] args) throws Exception {
		
//		List<SplashCard> cardsList = new ArrayList<SplashCard>();
//		cardsList.add(new TestCard("helen"));
//		cardsList.add(new TestCard("keke"));
//		cardsList.add(new TestCard("xixi"));
//		
//		SplashClient splashClient = new SplashClient();
//		CardSet cardSet = new CardSet();
//		cardSet.setPort(7776);
//		cardSet.setTargetName("localhost");
//		cardSet.setCards(cardsList);
//		System.out.println(splashClient.send(cardSet)+ "");
	}
}
